/**
 * @api {get} /api/admin/v1/accounts/analyse 用户统计
 * @apiGroup AdminUsersAccounts
 * @apiDescription 用户管理-用户统计
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.analyse = function ({}, {models: {UsersAccounts}}) {
    return UsersAccounts.analyseV2();
}

/**
 * @api {get} /api/admin/v1/accounts/browse 用户列表
 * @apiGroup AdminUsersAccounts
 * @apiDescription 用户管理-用户列表
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.browse = function ({query}, {models: {UsersAccounts, Users, associations}, controller}) {
    return UsersAccounts.findAndCountAll(controller.pagination({
        params: query,
        filters: ['domain', 'status', 'user_id'],
        likes: ['nickname', 'username']
    })).then(function (data) {
        return associations.relateOne(data, Users, 'user_id', 'user', ['id', 'image', 'username', 'nickname', 'tel']);
    });
}

/**
 * @api {get} /api/admin/v1/accounts/load 用户详情
 * @apiGroup AdminUsersAccounts
 * @apiDescription 用户管理-用户详情
 * @apiPermission 管理员(查看用户权限)
 * @apiVersion 1.0.0
 */
exports.load = function ({query}, {models: {UsersAccounts, Users}}) {
    return UsersAccounts.findOne({where: {id: query.id}}).then(function (account) {
        if (account.user_id) {
            return Users.findOne({
                where: {id: account.user_id},
                attributes: ['id', 'image', 'username', 'nickname', 'tel']
            }).then(function (user) {
                account.user = user;
                return account;
            });
        }
        return account;
    });
}

/**
 * @api {post} /api/admin/v1/accounts/add 用户添加
 * @apiGroup AdminUsersAccounts
 * @apiDescription 用户管理-用户添加
 * @apiPermission 管理员(添加用户权限)
 * @apiVersion 1.0.0
 */
exports.add = function ({body}, {models: {UsersAccounts}}) {
    return UsersAccounts.create(body).then(function (account) {
        return {success: true, data: account};
    });
}

/**
 * @api {post} /api/admin/v1/accounts/edit 用户编辑
 * @apiGroup AdminUsersAccounts
 * @apiDescription 用户管理-用户编辑
 * @apiPermission 管理员(编辑用户权限)
 * @apiVersion 1.0.0
 */
exports.edit = function ({body}, {models: {UsersAccounts}}) {
    let where = {id: body.id};
    delete body.id;
    return UsersAccounts.update(body, {where: where}).then(function (result) {
        if (!result[0]) {
            return {success: false};
        }
        return UsersAccounts.findOne({where: where}).then(function (account) {
            return {success: true, data: account};
        });
    });
}

/**
 * @api {post} /api/admin/v1/accounts/delete 用户删除
 * @apiGroup AdminUsersAccounts
 * @apiDescription 用户管理-用户删除
 * @apiPermission 管理员(删除用户权限)
 * @apiVersion 1.0.0
 */
exports.delete = function ({body}, {models: {UsersAccounts}}) {
    return UsersAccounts.destroy({where: {id: body.id}}).then(function () {
        return {success: true};
    });
}